package com.lcj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcj.dto.*;
import com.lcj.entity.*;
import com.lcj.mapper.*;
import com.lcj.service.IArticleService;
import com.lcj.utils.JwtService;
import com.lcj.utils.UserUtils;
import com.lcj.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)

public class ArticleService implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagsMapper articleTagsMapper;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleFavoritesMapper articleFavoritesMapper;



    @Override
    public int createArticle(ArticleInfo articleInfo, long userId) {
        System.out.println(articleInfo.toString());
        Articles articles = new Articles();
        articles.setTitle(articleInfo.getArticle().getTitle());
        articles.setDescription(articleInfo.getArticle().getDescription());
        articles.setBody(articleInfo.getArticle().getBody());

        articles.setUserId(userId);
        articleMapper.insert(articles);
        Long AId = articles.getId();
        articleInfo.getArticle().getTagList().forEach(tagName -> {
            QueryWrapper<Tags> wrapper = new QueryWrapper<>();
            wrapper.eq("name", tagName);
            Tags tags = tagMapper.selectOne(wrapper);
            ArticleTags articleTags = new ArticleTags();
            articleTags.setArticleId(AId);
            if (tags == null) {
                Tags tagsTmp = new Tags();
                tagsTmp.setName(tagName);
                tagMapper.insert(tagsTmp);
                Long tagssId = tagsTmp.getId();
                articleTags.setTagId(tagssId);
            } else {

                articleTags.setTagId(tags.getId());

            }
            articleTagsMapper.insert(articleTags);
        });
        return 1;

    }

    @Override
    public ArticleInfoVo getArticle(long id) {
        ArticleVo articleInfo = articleMapper.getArticleInfo(id);
        if (articleInfo.getStringTags() != null) {
            String[] arr = articleInfo.getStringTags().split(",");
            List<String> stringList = Arrays.asList(arr);
            articleInfo.setTagList(stringList);
        }
        Long loginUserId = UserUtils.getLoginUserId();
        QueryWrapper<ArticleFavorites> articleFavoritesQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ArticleFavorites> eq = articleFavoritesQueryWrapper.eq("user_id", loginUserId).eq("article_id", id);
        ArticleFavorites articleFavorites = articleFavoritesMapper.selectOne(eq);
        if(articleFavorites != null){
            articleInfo.setFavorited(true);
        }else {
            articleInfo.setFavorited(false);
        }
        Profiles profiles = profileService.getProfiles(articleInfo.getAuthor().getUsername());
        Profile profile = profiles.getProfile();
        articleInfo.getAuthor().setFollowing(profile.isFollowing());
        ArticleInfoVo articleInfoVo = new ArticleInfoVo();
        articleInfoVo.setArticleVo(articleInfo);
        return articleInfoVo;
    }

    @Override
    public ArticlesVo getAllArticles(ArticleCondition articleCondition) {

        List<ArticleVo> allArticles = articleMapper.getAllArticles(articleCondition);
        for (ArticleVo articlesVo : allArticles) {
            Profiles profiles = profileService.getProfiles(articlesVo.getAuthor().getUsername());
            Profile profile = profiles.getProfile();
            articlesVo.getAuthor().setFollowing(profile.isFollowing());
            if (articlesVo.getStringTags() != null) {

                String[] arr = articlesVo.getStringTags().split(",");
                List<String> stringList = Arrays.asList(arr);
                articlesVo.setTagList(stringList);
            }
            Long id = articlesVo.getId();
            Long loginUserId = UserUtils.getLoginUser().getId();
            QueryWrapper<ArticleFavorites> articleFavoritesQueryWrapper = new QueryWrapper<>();
            QueryWrapper<ArticleFavorites> eq = articleFavoritesQueryWrapper.eq("user_id", loginUserId).eq("article_id", id);
            ArticleFavorites articleFavorites = articleFavoritesMapper.selectOne(eq);
            if(articleFavorites != null){
                articlesVo.setFavorited(true);
            }else {
                articlesVo.setFavorited(false);
            }
        }
        int articleCount = articleMapper.getArticleCount(articleCondition);
        ArticlesVo articlesVo = new ArticlesVo();
        articlesVo.setArticles(allArticles);
        articlesVo.setArticlesCount(articleCount);
        return articlesVo;
    }

    @Override
    public ArticlesNBVo getARticlesByFeed() {
        Long id = UserUtils.getLoginUser().getId();
        List<ArticleNBVo> articlesByFeed = articleMapper.getArticlesByFeed(id);
        for (ArticleNBVo articleNBVo : articlesByFeed) {
            Profiles profiles = profileService.getProfiles(articleNBVo.getAuthor().getUsername());
            Profile profile = profiles.getProfile();
            articleNBVo.getAuthor().setFollowing(profile.isFollowing());
            if (articleNBVo.getStringTags() != null) {

                String[] arr = articleNBVo.getStringTags().split(",");
                List<String> stringList = Arrays.asList(arr);
                articleNBVo.setTagList(stringList);
            }
            Long loginUserId = UserUtils.getLoginUser().getId();
            Long articleId = articleNBVo.getArticleId();
            QueryWrapper<ArticleFavorites> articleFavoritesQueryWrapper = new QueryWrapper<>();
            QueryWrapper<ArticleFavorites> eq = articleFavoritesQueryWrapper.eq("user_id", loginUserId).eq("article_id", articleId);
            ArticleFavorites articleFavorites = articleFavoritesMapper.selectOne(eq);
            if(articleFavorites != null){
                articleNBVo.setFavorited(true);
            }else {
                articleNBVo.setFavorited(false);
            }

        }


        ArticlesNBVo articlesNBVo = new ArticlesNBVo();
        articlesNBVo.setArticles(articlesByFeed);
        articlesNBVo.setArticlesCount(articlesByFeed.size());
        return articlesNBVo;
    }

    @Override
    public ArticleInfoVo updateArticle(Long aid, ArticleInfo articleInfo) {
        Articles articles = new Articles();
        articles.setId(aid);
        if (articleInfo.getArticle().getTitle() != null){
        articles.setTitle(articleInfo.getArticle().getTitle());}
        if (articleInfo.getArticle().getDescription() != null){
            articles.setDescription(articleInfo.getArticle().getDescription());
        }
        if (articleInfo.getArticle().getBody() != null){
            articles.setBody(articleInfo.getArticle().getBody());
        }
        articles.setUpdatedAt(Timestamp.from(Instant.now()));
        articleMapper.updateById(articles);
        ArticleInfoVo article = getArticle(aid);

        return article;
    }

    @Override
    public void deleteArticle(Long aid) {
        articleMapper.deleteById(aid);
    }

    @Override
    public CommentDto createComments(Long aid, CommentInfoVo comment) {
        CommentVo comment1 = comment.getComment();
        String body = comment1.getBody();
        Long loginId = UserUtils.getLoginUser().getId();
        articleMapper.createComments(aid, body,loginId);
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", aid);
        wrapper.eq("user_id", loginId);
        wrapper.eq("body", comment1.getBody());
        Comments comments = commentsMapper.selectOne(wrapper);
        if (comments != null) {
            CommentDto commentDto = new CommentDto();
            commentDto.setId(comments.getId());
            commentDto.setCreatedAt(new Date(comments.getCreatedAt().getTime()));
            commentDto.setUpdatedAt(new Date(comments.getUpdatedAt().getTime()));
            commentDto.setBody(comments.getBody());
            QueryWrapper<Users> userWrapper = new QueryWrapper<>();
            userWrapper.eq("id", comments.getUserId());
            Users users = userMapper.selectOne(userWrapper);
            Author author = new Author();
            author.setUsername(users.getUsername());
            author.setBio(users.getBio());
            author.setImage(users.getImage());


           commentDto.setAuthor(author);
            return commentDto;
        }else {
            return null;
        }



    }

    @Override
    public CommentsDto getComments(Long aid) {
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        QueryWrapper<Comments> commentsQueryWrapper = wrapper.eq("article_id", aid);
        List<Comments> commentsList = commentsMapper.selectList(commentsQueryWrapper);
        System.out.println("ccccc"+ commentsList.size());

        CommentsDto commentsDto = new CommentsDto();
        List<CommentDto> commentDtos = new ArrayList<>();
        for( Comments comment: commentsList){
            QueryWrapper<Users> userWrapper = new QueryWrapper<>();
            userWrapper.eq("id", comment.getUserId());
            Users users = userMapper.selectOne(userWrapper);
            Author author = new Author();
            author.setUsername(users.getUsername());
            author.setBio(users.getBio());
            author.setImage(users.getImage());
            CommentDto commentDto = new CommentDto();
            commentDto.setId(comment.getId());
            commentDto.setCreatedAt(new Date(comment.getCreatedAt().getTime()));
            commentDto.setUpdatedAt(new
                    Date(comment.getUpdatedAt().getTime()));
            commentDto.setBody(comment.getBody());
            System.out.println(comment.getBody());

            commentDto.setAuthor(author);
            commentDtos.add(commentDto);
        }
commentsDto.setComments(commentDtos);
        return commentsDto;
    }

    @Override
    public void deleteComments(Long aid, Long cid) {
        QueryWrapper<Comments> eq = new QueryWrapper<Comments>().eq("article_id", aid).eq("id", cid);
        commentsMapper.delete(eq);
    }

    @Override
    public ArticleInfoVo favoriteArticle(Long aid) {
        Users user = UserUtils.getLoginUser();
        Long id = user.getId();
        QueryWrapper<ArticleFavorites> articleFavoritesQueryWrapper = new QueryWrapper<>();
        articleFavoritesQueryWrapper.eq("user_id", id).eq("article_id", aid);
        ArticleFavorites articleFavorites = articleFavoritesMapper.selectOne(articleFavoritesQueryWrapper);
        if (articleFavorites == null) {
            ArticleFavorites articleFavorites1 = new ArticleFavorites();
            articleFavorites1.setArticleId(aid);
            articleFavorites1.setUserId(id);

            articleFavoritesMapper.insert(articleFavorites1);
            return getArticle(aid);
        }else {
            throw new RuntimeException("你已经收藏过了");
        }

    }

    @Override
    public ArticleInfoVo unFavoriteArticle(Long aid) {
        Users user = UserUtils.getLoginUser();
        Long id = user.getId();
        QueryWrapper<ArticleFavorites> articleFavoritesQueryWrapper = new QueryWrapper<>();
        articleFavoritesQueryWrapper.eq("user_id", id).eq("article_id", aid);
        articleFavoritesMapper.delete(articleFavoritesQueryWrapper);
        return getArticle(aid);
    }


}
